
var orderModel = require("../models/order.model");
var flightModel = require("../models/flight.model");
var moment = require("moment");
var userModel = require("../models/user.model");
var nodeRSA = require("node-rsa");
var config = require("../config.lib");
var testFunc= require('./publicFunc/travelTest.js')

//获取到设置state的initalValues等各种数据
function getInitalValues(req, res, next, cb){
    orderModel.findById(req.query.id, (err, doc)=>{
        if(err){
            res.json({
                success: false,
                description: "继续支付查询订单出错"
            })
        }else{
            if(doc){//查询航班信息
                let filter = {
                    startCity: doc.start.city,
                    startAirport: doc.start.airport,
                    startTime: doc.start.time,
                    endCity: doc.end.city,
                    endAirport: doc.end.airport,
                    endTime: doc.end.time
                }
                flightModel.find(filter,(err, data)=>{
                    if(err){
                        console.error(err);
                        res.json({
                            success: false,
                            description: "继续支付查询航班出错"
                        })
                    }else{
                        data = data[0];
                        if(data){
                            //查询到了结果,这里结果还要进行用户行程冲突检测。
                            let dataobj = {};
                            data.economyClass.afterPrice = (data.economyClass.price * data.economyClass.discount).toFixed(2);
                            data.businessClass.afterPrice = (data.businessClass.price * data.businessClass.discount).toFixed(2);
                            data.firstClass.afterPrice = (data.firstClass.price * data.firstClass.discount).toFixed(2);

                            dataobj.economyClass = data.economyClass;
                            dataobj.businessClass = data.businessClass;
                            dataobj.firstClass = data.firstClass;
                            dataobj._id = data._id;
                            dataobj.flight = {
                                baby: data.baby,
                                child: data.child,
                                company: data.company,
                                food: data.food,
                                plane: data.plane,
                                type: data.type
                            };
                            dataobj.start = {
                                airport: data.startAirport,
                                city: data.startCity,
                                time: data.startTime
                            };
                            dataobj.end = {
                                airport: data.endAirport,
                                city: data.endCity,
                                time: data.endTime
                            }
                            let values = {
                                data:{
                                    goData: doc,
                                    goID: dataobj._id
                                },
                                initalValues:{
                                    goTrip: {...dataobj, id: dataobj._id},
                                    goType: doc.classType + "",
                                    toTrip: {},
                                    toType: ""
                                },
                                values:{
                                    contact: doc.contact,
                                    number: (()=>{
                                        let passenger = doc.passenger,
                                            number = 0;
                                        for(let i = 0; i < passenger.length; i++){
                                            if(passenger[i].type !== "2"){
                                                number++;
                                            }
                                        }
                                        return number;
                                    })(),
                                    passenger: (()=>{
                                        let arr = [], obj = {}, passenger = doc.passenger;
                                        for(let i = 0; i < passenger.length; i++){
                                            obj = {};
                                            obj.type = passenger[i].type;
                                            switch( passenger[i].type){
                                                case "0": obj = {//成人
                                                    IDnumber: passenger[i].IDnumber,
                                                    construction: 1,
                                                    fuel: 1,
                                                    name:  passenger[i].name,
                                                    pay: 1,
                                                    phone:  passenger[i].phone,
                                                    type: passenger[i].type
                                                }; break;
                                                case "1": obj = {//儿童
                                                    IDnumber: passenger[i].IDnumber,
                                                    construction: 0,
                                                    fuel: 0.5,
                                                    name:  passenger[i].name,
                                                    pay: 0.5,
                                                    phone:  passenger[i].phone,
                                                    type: passenger[i].type
                                                }; break;
                                                case "2": obj = {//婴儿
                                                    IDnumber: passenger[i].IDnumber,
                                                    construction: 0,
                                                    fuel: 0,
                                                    name:  passenger[i].name,
                                                    pay: 0.1,
                                                    phone:  passenger[i].phone,
                                                    type: passenger[i].type
                                                }; break;
                                            }
                                            arr.push(obj);
                                        }
                                        return arr;
                                    })()
                                }
                            };
                            //行程检测后再返回，bookController
                            cb(values);
                        }else{
                            res.json({
                                success: false,
                                description: "继续支付查询航班为空"
                            })
                        }
                    }
                })//flightModel.find(filter,(err, data)=>{
            }else{
                res.json({
                    success: false,
                    description: "继续支付查询订单为空"
                })
            }
        }
    });
}

module.exports={
    getList:function(req, res, next){
        let  query = req.query,
            filter = {};

        switch(query.type){//0所有订单
            case "1":{//已出行
                filter = {
                    "start.time" : {$lt: moment().format("YYYY-MM-DD HH:mm")},
                    state: 2
                }
            };break;
            case "2":{//未出行
                filter = {
                    "start.time" : {$gt: moment().format("YYYY-MM-DD HH:mm")},
                    state: 2
                }
            };break;
            case "3":{//待支付
                filter = { 
                    $or:[{state: 0}, {state: 1}]
                }
            };break;
        }
        //时间
        if(query.begin && query.end){
            filter = {
                "start.time" : { $gte: query.begin, $lte: query.end }
            }
        }else if(query.begin){
            filter = {
                "start.time" : { $gte: query.begin }
            }
        }else if(query.end){
            filter = {
                "start.time" : { $lte: query.end }
            }
        }
        filter.username = query.username;
        filter.deleted = false;
        orderModel.find(filter, (err, data) =>{
            if(err){
                console.error(err);
                res.json({
                    success: false,
                    description: "获取列表失败"
                })
            }else{
                res.json({
                    success: true,
                    data: data
                })
            }
        } )
    },
    deleteItem: function(req, res, next){
        let body = JSON.parse(req.body.data);
        console.log("删除的body", body);
        orderModel.findByIdAndUpdate(body.values._id, {...body.values, deleted : true}, {new: true}, (err, data)=>{
            if(err){
                res.json({
                    success: false,
                    description:"订单删除出错",
                })
            }else{
                res.json({
                    success: true,
                    description:"订单删除成功",
                    data:data
                })
            }
        });
    },
    getPersonalInf: function(req, res, next){
        //获取用户的信息
        userModel.find({username: req.query.username}, (err, data)=>{
            if(err){
                console.error(err);
                res.json({
                    success: false,
                    description:"查询用户信息失败"
                })
            }else{
                data = data[0];
                if(data){
                    let nowdata = JSON.parse(JSON.stringify(data));
                    delete nowdata.password;
                    res.json({
                        success: true,
                        data:nowdata
                    })
                }else{
                    res.json({
                        success: false,
                        description:"该用户信息出问题了"
                    })
                }
                
            }
        })
    },
    usernameRepeatTest:function(req, res, next){
        userModel.find({username: body.query.username},(err, data)=>{
            if(err){
                res.json({
                    success: false,
                    description:"用户名重复检测出错",
                })
            }else{
                if(data.length){
                    res.json({
                        success: true,
                        data:{
                            state: 0//用户名存在
                        }
                    })
                }else{
                    res.json({
                        success: true,
                        data:{
                            state: 1
                        }
                    })
                }
            }
        })
    },
    userChange: function(req, res, next){
        //邮箱修改后要重新验证吗???，暂时不写，最好要验证的吧。
        let body = JSON.parse(req.body.data),
            values = JSON.parse(req.body.data);

        delete values._id;
        userModel.findByIdAndUpdate(body._id, values,{new: true}, (err, data)=>{
            if(err){
                console.error(err);
                res.json({
                    success: false,
                    description:"用户信息更新失败",
                })
            }else{
                res.json({
                    success: true,
                    description:"更新成功",
                    data:data
                })
            }
        })        
    },
    changePassword: function(req, res, next){
        let body = JSON.parse(req.body.data),
            rsa = new nodeRSA(config.privateKey),
            passwords = {};

        passwords.nowPassWord = rsa.decrypt(body.nowPassWord, "utf8");//旧密码
        passwords.password = rsa.decrypt(body.password, "utf8");//新密码
        //改变,还要解密的。
        userModel.findOne({username: body.username}, (err, doc)=>{
            if(err){
                console.error(err);
                res.json({
                    success: false,
                    description: "更新密码查询用户出错"
                })
            }else{
                if(doc){
                    if(doc.password === passwords.nowPassWord){
                        let newdoc =  JSON.parse(JSON.stringify(doc));
                        delete newdoc._id;

                        userModel.findByIdAndUpdate(doc._id, {...newdoc, password: passwords.password}, {new: true},(err, data)=>{
                            if(err){
                                console.error(err);
                                res.json({
                                    success: false,
                                    description:"更新密码出错"
                                })
                            }else{
                                res.json({
                                    success: true,
                                    data:{
                                        state: 1//更新密码成功
                                    }
                                })
                            }
                        })
                    }else{
                        res.json({
                            success: true,
                            data:{
                                state: 0//用户的秘密错误
                            }
                        })
                    }
                    
                }else{
                    res.json({
                        success: false,
                        description: "更新密码查不到用户结果"
                    })
                }
            }
        })// userModel.findOne({username: body.username}
    },
    getDataAndInitalValues: function(req, res, next){
        getInitalValues(req, res, next, (values)=>{
            //乘客冲突检测
            testFunc.isConflict(req, res, next, values, (req, res, next, flag) =>{
                if(flag){
                    res.json({
                        success: true,
                        description:"乘客行程冲突",
                        data: {
                            state: 1,
                        }
                    })
                }else{
                    res.json({
                        success: true,
                        data: {
                            state: 0,
                            data: values
                        }
                    })
                }
            })
        });
    },
    getUnsubscribeValues: function(req, res, next){
        getInitalValues(req, res, next, (values)=>{
            res.json({
                success: true,
                data: values
            })
        });
    }
}
